import * as fs from 'fs'
import * as path from 'path'
import * as util from 'util'
import { Application } from 'egg'
import { Repository } from './uow'

export default async (app: Application) => {
  const { dataPath } = app.config.settings
  let exists = await util.promisify(fs.exists)(dataPath)
  if (!exists) {
    await util.promisify(fs.mkdir)(dataPath)
    app.logger.info('mkdir data path', dataPath)
  }
  const backupPath = path.join(dataPath, 'backup')
  exists = await util.promisify(fs.exists)(backupPath)
  if (!exists) {
    await util.promisify(fs.mkdir)(backupPath)
    app.logger.info('mkdir backup path', backupPath)
  }

  const replacer = (key: string, value: any) => {
    return value === null ? undefined : value
  }

  const toFile = async (name: string, repository: Repository) => {
    const data = await repository.all()
    if (data.length) {
      const fileName = path.join(backupPath, `${name}.json`)
      await util.promisify(fs.writeFile)(fileName, JSON.stringify(data, replacer))
      app.logger.info('toFile', name, data.length)
    }
  }

  for (const key of Object.keys(app.model)) {
    if (app.model[key].findAndCountAll) {
      await toFile(key, app.uow[key])
      // app.logger.info('model', key, app.uow[key].name)
    }
  }
}
